import React, { Component } from 'react';
import style from './main.module.css';
import { Select,Icon,Table,Menu,Dropdown,Input,Switch,Button } from 'antd';
import { NavLink } from 'react-router-dom';
import MainContent from './maincontent/maincontent';
import cookie from 'react-cookies';
import $ from 'jquery';
const { Search } = Input;
const { Option, OptGroup } = Select;

class MainList extends Component {
  state={
    header_idx:'',
    tabMod:'',
    header_list:[],
    listid:'', //栏目id
    selectedRowKeys: [], // Check here to configure the default column
    columns:[],
    selectlength:0,
    oldtabMod:'',
    data:[],
    datalength:102,
    datalimit:10,
    checked:true, //显示隐藏
    allsection:[],//所有分类
    title:'', //标题名
    if_action:false, //是否打开转移选择弹窗
    action_mod:'', //转移、复制操作类型
    goto_id:'', //要移动去的栏目id
  }

  componentDidMount() {
    console.log(this.props)
    const id = cookie.load('mainlist')?cookie.load('mainlist').listid:this.state.listid;
    this.get_psection(this.props.id)
  }

  get_psection=(id)=>{  
    const that = this
    $.ajax({
      url:`/${this.props.tabUrl}`,
      type:'GET',
      data:{
        act:'psection',
        id,
      },
      dataType:'json',
      success(e){
        console.log(e)
        if(e.status == 1){
          that.setState({
            header_list:e.data,
            listid:cookie.load('mainlist')?cookie.load('mainlist').listid:e.data.find(e=>e.id).id
          })
          that.gocolumns(that.props.tabMod,cookie.load('mainlist')?cookie.load('mainlist').listid:e.data.find(e=>e.id).id)
          that.getallsection(cookie.load('mainlist')?cookie.load('mainlist').listid:e.data.find(e=>e.id).id)
        }else{
          alert(e.msg)
        }
      }
    })
  }

  headerClick=(e)=>{
    this.gocolumns(this.props.tabMod,e.id)
    this.getallsection(e.id)
    cookie.save('mainlist',{listid:e.id},{path:'/'})
  }

  onSelectChange = selectedRowKeys => {
    // console.log('selectedRowKeys changed: ', selectedRowKeys);
    this.setState({ selectedRowKeys });
  };

  nameBlur=(id,e)=>{
    // console.log(id,e.target.value)
    $.ajax({
      url:`${this.props.tabUrl}`,
      type:'GET',
      data:{
        act:'submit',
        id,
        title:e.target.value
      },
      dataType:'json',
      success(e){
        console.log(e)
      }
    })
  }

  changeDisplay=(id)=>{  
    let data = this.state.data;
    let ifdisplay = '';
    const that = this;
    data.map(e=>{if(e.id==id){e.ifdisplay=='0'?e.ifdisplay='1':e.ifdisplay='0';ifdisplay = e.ifdisplay;}});
    console.log(ifdisplay)
    $.ajax({
      url:`${this.props.tabUrl}`,
      type:'GET',
      data:{
        act:'submit',
        id,
        ifdisplay,
      },
      dataType:'json',
      success(e){
        console.log(e)
        if(e.status == 1){
          that.setState({
            data
          })
        }else{
          alert(e.msg)
        }
      }
    })
  }

  histBlur=(id,e)=>{
    // console.log(id,e.target.value)
    $.ajax({
      url:`${this.props.tabUrl}`,
      type:'GET',
      data:{
        act:'submit',
        id,
        hits:e.target.value
      },
      dataType:'json',
      success(e){
        console.log(e)
      }
    })
  }

  orderstBlur=(id,e)=>{
    $.ajax({
      url:`${this.props.tabUrl}`,
      type:'GET',
      data:{
        act:'submit',
        id,
        orders:e.target.value
      },
      dataType:'json',
      success(e){
        console.log(e)
      }
    })
  }

  word_seach=(value, event)=>{
    // console.log(value, event)
    const that = this;
    $.ajax({
      url:`/${this.props.tabUrl}`,
      type:'GET',
      data:{
        act:'word_seach',
        id:this.state.listid,
        val:value!=''?value:'-1',
      },
      dataType:'json',
      success(e){
        let data = e.data
        for(let obj of data){
          obj.action = [
            {
              name:'预览',
              preview:true
            },
            {
              name:'修改',
              url:{
                pathname:`/home/modify/url/${that.props.tabUrl}/act/${that.state.act}/id/${obj.id}`,
                state:{
                  ifrepathname:true,
                  repathname:'/home/'+ that.props.tabUrl,
                  p_key:''
                }
              }
            },
            {
              name:'删除',
              id:2,
              pid:1,
            }
          ]
        }
        that.setState({
          data
        })
      }
    })
  }

  select_change=(value)=>{
    const that = this;
    $.ajax({
      url:`/${this.props.tabUrl}`,
      type:'GET',
      data:{
        act:'select_seach',
        id:this.state.listid,
        val:value,
      },
      dataType:'json',
      success(e){
        let data = e.data
        for(let obj of data){
          obj.action = [
            {
              name:'预览',
              preview:true
            },
            {
              name:'修改',
              url:{
                pathname:`/home/modify/url/${that.props.tabUrl}/act/${that.state.act}/id/${obj.id}`,
                state:{
                  ifrepathname:true,
                  repathname:'/home/'+ that.props.tabUrl,
                  p_key:''
                }
              }
            },
            {
              name:'删除',
              id:2,
              pid:1,
            }
          ]
        }
        that.setState({
          data
        })
      }
    })
  }

  actionDelete=(id)=>{ //删除操作
    const that = this;
    // console.log(id)
    $.ajax({
      url:`/${this.props.tabUrl}`,
      type:'GET',
      data:{
        act:'delete',
        id,
      },
      dataType:'json',
      success(e){
        console.log(e)
        if(e.status == 1){
          let data = [];
          let obj = that.state.data;
          obj.map(s=>{if(s.id!=id){data.push(s)}})
          console.log(data)
          that.setState({
            data
          })
        }else{
          alert(e.msg);
        }
      }
    })
  }

  select_delete=()=>{ //已选中删除
    const that = this;
    const selectlen = that.state.selectedRowKeys
    console.log(this.state.selectedRowKeys)
    if(this.state.selectedRowKeys.length != 0){
      $.ajax({
        url:`/${this.props.tabUrl}`,
        type:'GET',
        data:{
          act:'select_delete',
          id:this.state.selectedRowKeys,
        },
        dataType:'json',
        success(e){
          console.log(e)
          if(e.status == 1){
            let data = [];
            let obj = that.state.data;
            obj.map(s=>{;
              if(!selectlen.find(i=>s.id == i)){ data.push(s)}
            })
            // console.log(data)
            that.setState({
              data
            })
          }else{
            alert(e.msg);
          }
        }
      })
    }
  }

  optionHandle=(mod)=>{ //转移、复制数据选mod，打开弹窗
    if(this.state.selectedRowKeys.length != 0){
      this.setState({
        if_action:true,
        action_mod:mod
      })
    }else{
      alert('请先选择数据')
    }
  }

  pop_close=()=>{ //关闭弹窗
    this.setState({
      if_action:false,
      goto_id:'',
      action_mod:''
    })
  }

  go_move=()=>{ //进行转移、复制数据操作
    const that = this;
    const selectlen = that.state.selectedRowKeys
    console.log(this.state.selectedRowKeys,this.state.action_mod,this.state.goto_id)
    if(this.state.goto_id!=''){
      $.ajax({
        url:`/${this.props.tabUrl}`,
        type:'GET',
        data:{
          act:this.state.action_mod,
          id:this.state.selectedRowKeys, //被转移数据id数组
          goid:this.state.goto_id, //要转移去的栏目
        },
        dataType:'json',
        success(e){
          console.log(e)
          if(e.status == 1){
            alert('操作成功')
            that.pop_close()
            window.location.reload()
          }else{
            alert('操作失败')
          }
        }
      })
    }else{
      alert('请选择要转移去的栏目')
    }
  }

  pop_select_change=(val)=>{ //选择要前往的id
    console.log(val)
    this.setState({
      goto_id:val
    })
  }

  gocolumns=(tabMod,id)=>{   //设置columns
    const that = this;
    let columns = [];
    //预览的下拉组件
    const menu_proview = (  
      <Menu className={style.menu_proview}>
        <Menu.Item>
          <a href="" target='_blank'>pc预览</a>
        </Menu.Item>
        <Menu.Item>
          <a href="" target='_blank'>手网预览</a>
        </Menu.Item>
      </Menu>
    )
    switch (tabMod) {
      case 'normal':
        this.setState({
          // data,
          columns: [
            {
              title:'编号',
              dataIndex:'id'
            },
            {
              title: '标题名',
              dataIndex: 'name',
              render:(e)=>(<Input onBlur={this.nameBlur.bind(this)} className={style.name} title={e} placeholder={e} />),
            },
            {
              title: '更新时间',
              dataIndex: 'time',
              render:(time)=>(time.text),
              sorter:(a,b)=>(a.time.timestamp - b.time.timestamp)
            },
            {
              title: '操作',
              dataIndex: 'action',
              render:obj=>(<ul className={style.action_ul}>
                {
                  obj.map((e,index)=>e.preview?'':(<li className={e.preview?style.preview:''} key={index}>
                    {e.name=='修改'?<NavLink to={e.url}>{e.name}</NavLink>:<a href={e.url} id={e.id} pid={e.pid} className={style.action}>{e.name}</a>}
                    </li>))
                }
              </ul>)
            },
          ]
        })
      break;
      case 'product':
          columns=[
            {
              title:'编号',
              dataIndex:'id'
            },
            {
              title:'列表图',
              dataIndex:'listimg',
              render:(e)=>(<img className={style.columns_img} imgurl={e} src={e!=''?e:'http://101.132.227.90:10086/static/media/201909041358059522758.247d5c6a.jpg'} alt=""/>)
            },
            {
              title: '标题名',
              dataIndex: 'name',
              render:(e,data)=>(<Input onBlur={this.nameBlur.bind(this,data.id)} onPressEnter={this.nameBlur.bind(this,data.id)} className={style.name} defaultValue={e} title={e} />),
            },
            {
              title: '分类',
              dataIndex: 'sectionname',
              render:(section)=>(section!=""?section:"无"),
            },
            {
              title: '是否显示',
              dataIndex: 'ifdisplay',
              // render:obj=>(<p onClick={this.changeDisplay.bind(this,obj)} className={style.ifdisplay}>{obj.map(e=>(e.default?e.mod:''))}</p>)
              render:(obj,data)=>(<Switch onChange={this.changeDisplay.bind(this,data.id)} checked={data.ifdisplay==1?true:false} checkedChildren={<Icon type="check" />} unCheckedChildren={<Icon type="close" />} defaultChecked />) 
            },
            {
              title: '点击量',
              dataIndex: 'hits',
              render:(e,data)=>(<Input onBlur={this.histBlur.bind(this,data.id)} onPressEnter={this.histBlur.bind(this,data.id)} className={style.hits} defaultValue={e} />),
              sorter:(a,b)=>(a.hits - b.hits)
            },
            {
              title: '排序',
              dataIndex: 'orders',
              render:(e,data)=>(<Input onBlur={this.orderstBlur.bind(this,data.id)} onPressEnter={this.orderstBlur.bind(this,data.id)} className={style.orders} defaultValue={e} />),
              sorter:(a,b)=>(a.orders - b.orders)
            },
            {
              title: '更新时间',
              dataIndex: 'updatatime',
              render:(time)=>(this.changetime(time)),
              sorter:(a,b)=>(a.updatatime - b.updatatime)
            },
            {
              title: '操作',
              dataIndex: 'action',
              render:obj=>(<ul className={style.action_ul}>
                {
                  obj.map((e,index)=>(<li className={e.preview?style.preview:''} key={index}>
                    {e.preview?<Dropdown trigger={['click']} overlay={menu_proview}><a>{e.name}<Icon type="down" /></a></Dropdown>:e.name=='修改'?<NavLink to={e.url}>{e.name}</NavLink>:<a href={e.url} id={e.id} onClick={this.actionDelete.bind(this,e.id)} className={style.action}>{e.name}</a>}
                    </li>))
                }
              </ul>)
            },
          ]
      break;
      case 'news':
        columns=[
          {
            title:'编号',
            dataIndex:'id'
          },
          {
            title:'列表图',
            dataIndex:'listimg',
            render:(e)=>(<img className={style.columns_img} imgurl={e} src={e!=''?e:'http://101.132.227.90:10086/static/media/201909041358059522758.247d5c6a.jpg'} alt=""/>)
          },
          {
            title: '标题名',
            dataIndex: 'name',
            render:(e,data)=>(<Input onBlur={this.nameBlur.bind(this,data.id)} onPressEnter={this.nameBlur.bind(this,data.id)} className={style.name} defaultValue={e} title={e} />),
          },
          {
            title: '分类',
            dataIndex: 'sectionname',
            render:(section)=>(section!=""?section:"无"),
          },
          {
            title: '是否显示',
            dataIndex: 'ifdisplay',
            // render:obj=>(<p onClick={this.changeDisplay.bind(this,obj)} className={style.ifdisplay}>{obj.map(e=>(e.default?e.mod:''))}</p>)
            render:(obj,data)=>(<Switch onChange={this.changeDisplay.bind(this,data.id)} checked={data.ifdisplay==1?true:false} checkedChildren={<Icon type="check" />} unCheckedChildren={<Icon type="close" />} defaultChecked />) 
          },
          {
            title: '点击量',
            dataIndex: 'hits',
            render:(e,data)=>(<Input onBlur={this.histBlur.bind(this,data.id)} onPressEnter={this.histBlur.bind(this,data.id)} className={style.hits} defaultValue={e} />),
            sorter:(a,b)=>(a.hits - b.hits)
          },
          {
            title: '排序',
            dataIndex: 'orders',
            render:(e,data)=>(<Input onBlur={this.orderstBlur.bind(this,data.id)} onPressEnter={this.orderstBlur.bind(this,data.id)} className={style.orders} defaultValue={e} />),
            sorter:(a,b)=>(a.orders - b.orders)
          },
          {
            title: '更新时间',
            dataIndex: 'updatatime',
            render:(time)=>(this.changetime(time)),
            sorter:(a,b)=>(a.updatatime - b.updatatime)
          },
          {
            title: '操作',
            dataIndex: 'action',
            render:obj=>(<ul className={style.action_ul}>
              {
                obj.map((e,index)=>(<li className={e.preview?style.preview:''} key={index}>
                  {e.preview?<Dropdown trigger={['click']} overlay={menu_proview}><a>{e.name}<Icon type="down" /></a></Dropdown>:e.name=='修改'?<NavLink to={e.url}>{e.name}</NavLink>:<a href={e.url} id={e.id} onClick={this.actionDelete.bind(this,e.id)} className={style.action}>{e.name}</a>}
                  </li>))
              }
            </ul>)
          },
        ]
      break;
    }
    //请求数据
    $.ajax({
      url:`/${this.props.tabUrl}`,
      dataType:'json',
      type:'GET',
      data:{
        act:'listall',
        id
      },
      success(e){
        // console.log(e.data)
        let data = e.data
        for(let obj of data){
          obj.action = [
            {
              name:'预览',
              preview:true
            },
            {
              name:'修改',
              url:{
                pathname:`/home/modify/act/modify/url/${that.props.tabUrl}/id/${obj.id}`,
                state:{
                  ifrepathname:true,
                  repathname:'/home/'+ that.props.tabUrl,
                  p_key:''
                }
              }
            },
            {
              name:'删除',
              id:obj.id,
            }
          ]
        }
        that.setState({
          selectedRowKeys:[],
          title:data.name,
          data,
          columns,
          listid:id,
          checked:e.ifdisplay == 1?true:false,
          tabMod:tabMod,
        })
      }
    })
  }

  changetime=(ntime)=>{
    if(ntime.length<=10){
      var time = new Date(parseInt(ntime)*1000)
    }else{
      var time = new Date(ntime)
    }
    return time.getFullYear()+'年'+Math.round(time.getMonth()+1)+'月'+time.getDate()+'日'+time.getHours()+'时'+time.getMinutes()+'分'+time.getSeconds()+'秒';
  }

  getallsection=(id)=>{  //获取所有栏目
    const that = this;
    $.ajax({
      url:`/${this.props.tabUrl}`,
      type:'GET',
      data:{
        act:'proSection',
        id
      },
      dataType:'json',
      success(obj){
        let e = obj.data
        let arr = []
        let sectionarr = []
        for(let i of e.filter(obj=>obj.pid == id&&obj.id != -1)){
          if(e.filter(obj=>obj.pid == i.id).length != 0){
            i.children = e.filter(obj=>obj.pid == i.id)
          }
          arr.push(i)
        }
        // console.log(arr)
        that.setState({
          allsection:arr
        })
      }
    })
  }

  render() { 
    const { selectedRowKeys } = this.state;
    const addurl = {
      pathname:`/home/modify/act/add/url/${this.props.tabUrl}/id/${this.state.listid}`,
      state:{
        ifrepathname:true,
        repathname:'/home/'+ this.props.tabUrl,
        p_key:'',
        pid:this.state.listid,
      }
    }
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
      hideDefaultSelections: true,
      selections: [
        {
          key: 'all-data',
          text: '全选',
          onSelect: () => {
            this.setState({
              selectedRowKeys: [...Array(this.state.datalimit).keys()], 
            });
          },
        },
        {
          key: 'odd',
          text: '选择偶数项',
          onSelect: changableRowKeys => {
            let newSelectedRowKeys = [];
            newSelectedRowKeys = changableRowKeys.filter((key, index) => {
              if (index % 2 !== 0) {
                return false;
              }
              return true;
            });
            this.setState({ selectedRowKeys: newSelectedRowKeys });
          },
        },
        {
          key: 'even',
          text: '选择奇数项',
          onSelect: changableRowKeys => {
            let newSelectedRowKeys = [];
            newSelectedRowKeys = changableRowKeys.filter((key, index) => {
              if (index % 2 !== 0) {
                return true;
              }
              return false;
            });
            this.setState({ selectedRowKeys: newSelectedRowKeys });
          },
        },
      ],
    };

    return (
      <div className={style.main}>
        <ul className={style.main_header}>
          {
            this.state.header_list.map((e,index)=>(<li key={index} className={this.state.listid===e.id?style.main_header_act:''} onClick={this.headerClick.bind(this,e)}>{e.name}</li>))
          }
        </ul>
        <div className={style.seach}>
          <div className={style.seach_list}>
            分类：
            <Select
              showSearch={true}
              style={{ width: 272 }}
              placeholder="搜索分类"
              onChange={this.select_change}
            >
              <Option value='-1'>所有分类</Option>
              {
                this.state.allsection.map((e)=>(
                  e.children?  
                  (<OptGroup key={e.id} label={e.name}>
                    {e.children?e.children.map(a=>(
                      <Option key={a.id} value={a.id}>{a.name}</Option>
                    )):''}
                  </OptGroup>):<Option key={e.id} value={e.id}>{e.name}</Option>
                ))
              }
            </Select>
          </div>
          <div className={style.seach_list}>
            文字搜索：
            <Search
              placeholder="文字搜索"
              style={{ width: 272 }}
              onSearch={this.word_seach}
            />
          </div>
          <div className={style.goseach}>搜索</div>
        </div>
        {/* <MainContent act={this.state.act} setcolumnsRef={e=>this.setcolumnsRef=e} tabMod={this.state.tabMod} tabUrl={this.props.tabUrl} /> */}

        <div className={style.content}> 
          <div className={style.add}>
            <NavLink className={style.add_a} to={addurl}>+ 添加</NavLink>
            <Select
              placeholder="操作"
              style={{ width: 88 }}
              value='操作'
            >
              <Option onClick={this.optionHandle.bind(this,'move')} value="move">移至</Option>
              <Option onClick={this.optionHandle.bind(this,'copy')} value="copy">复制</Option>
              <Option style={{display:'none'}} disabled value="操作" key="操作">操作</Option>
            </Select>
          </div>
          <div className={style.msg}>
            <Icon style={{color:'#1890FF'}} type="exclamation-circle" theme="filled" />
            <span className={style.msg_title}>已选择<p>{this.state.selectedRowKeys.length}项</p></span>
            <div className={style.msg_delete} onClick={this.select_delete}>删除</div>
            <div className={style.msg_alldata}>一共<p>{this.state.data.length}项</p></div>
          </div>
          <div className={style.tab}>
            <Table rowKey='id' rowSelection={rowSelection} columns={this.state.columns} dataSource={this.state.data} />
          </div>
        </div>

        <div className={style.pop} style={this.state.if_action?{dispay:'block'}:{display:'none'}}>
          <div className={style.popchild}>
            <div className={style.popchild_div01}>
              移动产品
              <Icon onClick={this.pop_close} type="close" />
            </div>
            <div className={style.popchild_div02}>
              <p>选择栏目</p>
              <Select
                showSearch={true}
                style={{ width: 260 }}
                placeholder="搜索分类"
                value={this.state.goto_id!=''?this.state.goto_id:'搜索分类'}
                onChange={this.pop_select_change}
              >
                {
                  this.state.header_list.map((e)=>(
                    <Option key={e.id} value={e.id} >{e.name}</Option>
                  ))
                }
              </Select>
            </div>
            <div className={style.popchild_div03}>
              <div className={style.btn_yes} onClick={this.go_move}>确定</div>
              <div className={style.btn_close} onClick={this.pop_close}>取消</div>
            </div>
          </div>
        </div>
      </div>
    );
  }
}
 
export default MainList;